package mnnu.ghbe.controller;

import mnnu.ghbe.dto.Result;
import mnnu.ghbe.entity.History;
import mnnu.ghbe.service.HistoryService;
import mnnu.ghbe.util.JwtUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/api/simulator/history")
public class HistoryController {

    @Autowired
    private HistoryService historyService;

    @Autowired
    private JwtUtil jwtUtil;

    /**
     * 根据JWT获取当前用户的历史记录
     * @param authorization JWT token
     * @return 历史记录列表
     */
    @GetMapping
    public Result<List<History>> getMyHistory(@RequestHeader("Authorization") String authorization) {
        try {
            String token = authorization.substring(7); // Remove "Bearer " prefix
            Long userId = jwtUtil.getUserIdFromToken(token);
            
            List<History> historyList = historyService.getUserHistory(userId);
            return Result.success(historyList);
        } catch (Exception e) {
            return Result.error(500,"获取历史记录失败: " + e.getMessage());
        }
    }
    
    /**
     * 清空当前用户的历史记录
     * @param authorization JWT token
     * @return 操作结果
     */
    @DeleteMapping("/clear")
    public Result<String> clearMyHistory(@RequestHeader("Authorization") String authorization) {
        try {
            String token = authorization.substring(7); // Remove "Bearer " prefix
            Long userId = jwtUtil.getUserIdFromToken(token);
            
            historyService.clearUserHistory(userId);
            return Result.success("历史记录已清空");
        } catch (Exception e) {
            return Result.error(500, "清空历史记录失败: " + e.getMessage());
        }
    }
}